from django.shortcuts import render
from django.http import HttpResponse
from . models import *
import os,time

###分类操作视图

#获取dash添加商品种类页面
def add_type_page(request):
	#获取所有分类信息，并使用path和id进行字段拼接，用于排序
	types = Types.objects.extra(select = {'_has':'concat(path,id)'}).order_by('_has')
	#遍历types，判断path中count的数量，用于判断商品分类的等级
	for v in types:
		n = v.path.count(',')-1
		v.name = '... '*n+v.name
    #封装返回数据dict
	re_info = {'types':types}

	return render(request,'dash/type/add_page.html',re_info)

#添加商品分类
def add_type(request):
	try:
		typee = Types()
		#获取分类type和pid,设置typee属性准备save
		typee.name = request.POST['name']
		typee.pid = request.POST['pid']
		#根据获取到的pid判断当前商品分类是否为顶级分类(pid=0为顶级分类)
		if request.POST['pid'] == '0':
			typee.path = '0,'
		else:
			#如果不是顶级分类，则根据当前pid查询父类的path
			father = Types.objects.get(id=request.POST['pid'])
			typee.path = father.path + str(father.id) + ','
		typee.save()
		#返回商品分类列表页
		return HttpResponse('<script>alert("添加分类成功");location.href="/dashboard/type/type_list_page"</script>')
	except:
		return HttpResponse('<script>alert("添加分类失败");location.href="/dashboard/type/type_list_page"</script>')

#获取dash分类列表页面
def type_list_page(request,p_index=1):
	#获取所有分类信息，并使用path和id进行字段拼接，用于排序
	types = Types.objects.extra(select = {'_has':'concat(path,id)'}).order_by('_has')

	#多条件筛选判断
	if request.GET.get('search_type') == 'type_name':
		types = Types.objects.filter(name__contains = request.GET.get('keywords'))
		
	#遍历types，判断path中count的数量，用于判断商品分类的等级
	for v in types:
		n = v.path.count(',')-1
		v.name = '... '*n+v.name
		if v.pid == 0:
			v.type_name = '顶级分类'
		else:
			typee = Types.objects.get(id=v.pid)
			v.type_name = typee.name

	#获取分页数据
	from django.core.paginator import Paginator
	p_index = int(p_index)
	#进行数据分页，实例化对象，设置每页返回数据的条数
	p = Paginator(types,5)
	#获取分页后的数据
	types = p.page(p_index)
	
	#封装返回数据
	re_info = {'types':types}

	return render(request,'dash/type/list_page.html',re_info)

#删除商品分类
def del_type(request):
	#判断当前分类是否还有父类分类
	flag = Types.objects.filter(pid=request.GET['type_id']).count()

	if flag == 0 :
		#无父类分类，可直接删除
		typee = Types.objects.get(id=request.GET['type_id'])
		typee.delete()
		#返回分类列表页
		return HttpResponse('<script>alert("商品分类删除成功");location.href="/dashboard/type/type_list_page"</script>')
	else :
		#存在父类分类，不可直接删除
		return HttpResponse('<script>alert("商品分类删除失败");location.href="/dashboard/type/type_list_page"</script>')

#编辑商品分类信息
def edit_type(request):
	try:
		typee = Types.objects.get(id=request.GET['id'])
		typee.name = request.GET['name']
		typee.save()
		return HttpResponse(0)
	except :
		return HttpResponse(1)









		



	













